<template>
  <div class="dataFusion">
    <el-row :gutter="20">
      <el-col
        :span="11"
        style="
          border-radius: 10px;
          box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
          background-color: #fff;
          width: 100%;height: calc(100vh - 20px);
        "
      >
        <div class="grid-content ep-bg-purple">
          <h4 class="header_1">数据融合</h4>
          <div class="fusionData">
<!--            <div class="title">待融合数据列表</div>
 -->
          <div class="title">选择待融合数据文件</div>
            <el-input
              v-model="fileName"
              style="max-width: 100%"
              class="input-with-select"
            >
              <template #append>
                <el-upload
                  class="upload-demo"
                  action="#"
                  :limit="3"
                  accept=".mat,.xlsx,.csv"
                  :multiple="true"
                  :auto-upload="false"
                  :show-file-list='false'
                  :on-change="handleChange"
                >
                  <template #trigger>
                    <el-button type="primary">...</el-button>
                  </template>
                </el-upload>
              </template>
            </el-input>
          <div class="file-list" >
            <div v-for="(item, index) in fileUpList" :key="index" class="file-item">
              <span>{{ item.name }}</span>
              <el-button link type="primary" @click="removeFile(index)">删除</el-button>
            </div>
          </div>
          <!-- <div class="file-list">
            <div v-for="(item, index) in fileUpList" :key="index" class="file-item">
              <span>{{ item }}</span>
              <el-button type="text" @click="removeFile(index)">删除</el-button>
            </div>
          </div> -->
        </div>

        </div>
        <div class="fuseWay">
          <div class="title">融合方法</div>
          <el-select v-model="c_way" style="width: 100%">
            <el-option
              v-for="item in fuseWay_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <!-- <div class="storePath">
          <div class="title">选择保存路径</div>
          <el-input
            v-model="s_path"
            style="max-width: 100%"
            class="input-with-select"
          >
            <template #append>
              <el-button @click="handleSavePath">...</el-button>
            </template>
          </el-input>
        </div> -->
        <div class="btns">
          <el-button
            type="primary"
            style="padding: 10px 40px"
            @click="uploadBtn"
            :disabled="isDisabled"
            >{{ b_fusion }}</el-button>
          <!-- <el-button type="warning" style="padding: 10px 20px">暂停</el-button>
          <el-button type="danger" style="padding: 10px 20px">结束</el-button> -->
        </div>
      </el-col>
      <el-col :span="0.5"></el-col>
      <el-col
        :span="12"
        style="
          border-radius: 10px;
          box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
          background-color: #fff;
          width: 100%;height: calc(100vh - 20px);
        "
      >
        <div class="grid-content ep-bg-purple">
          <!-- <h4 class="header_2">状态栏</h4> -->
          <div class="over_btn">
            <el-tag :type="tagType" style="padding: 15px 39%; font-size: 18px">
              {{ fusion_res }}
            </el-tag>
          </div>
          <div class="upchart"></div>
          <div class="midchart"></div>
          <div class="downchart"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import echarts from "@/plugins/echarts";
import { ref, onMounted, computed } from "vue";
import { ScatterChart } from "echarts/charts";
import { BrushComponent } from 'echarts/components';
import { codeFusion } from '@/api/dataProcessing'
import { message } from "@/utils/message";

echarts.use([ScatterChart]);
echarts.use([BrushComponent]);

const fileName = ref("");
const c_way = ref(0);
const s_path = ref("");
const b_fusion = ref("开始融合")
const fusion_res = ref("未进行数据融合")
const isDisabled = ref(false)
const chartYName = ref("储纱机构振动数据")

const fuseWay_options = [
  {
    value: 0,
    label: "卡尔曼滤波"
  },
];
onMounted(() => {
  getChart();
  getChart1();
});

let myChart = ref();
function getChart() {
  var chart = document.querySelector(".upchart");
  myChart.value = echarts.init(chart);
  var option = {
    title: {
      text: "数据融合前",
      textStyle: {
        fontSize: 15 // 设置字号为 14px
      }
    },
    grid: {
      left: "3%",
      right: "7%",
      bottom: "7%",
      containLabel: true
    },
    legend: {
      right: "15%",
      data: ["固定储纱辊", "摆动储纱辊","夹纱板"],
      icon: "roundRect",
      top: "5%",
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      // trigger: 'axis',
      showDelay: 0,
      formatter: function (params) {
        if (params.value.length > 1) {
          return (
            params.seriesName +
            " :<br/>" +
            params.value[0] +
            " " +
            params.value[1] +
            " "
          );
        } else {
          return (
            params.seriesName +
            " :<br/>" +
            params.name +
            " : " +
            params.value +
            " "
          );
        }
      },
      axisPointer: {
        show: true,
        type: "cross",
        lineStyle: {
          type: "dashed",
          width: 1
        }
      }
    },
    xAxis: [
      {
        type: "category",
        scale: true,
        axisLabel: {
          formatter: "{value} "
        },
        splitLine: {
          show: false
        }
      }
    ],
    yAxis: [
      {
        name: chartYName.value,
        type: "value",
        nameRotate:0.1,
        scale: true,
        axisLabel: {
          formatter: "{value} "
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: "固定储纱辊",
        type: "scatter",
        symbolSize: 5,
        emphasis: {
          focus: "series"
        },
        data: [[161.2, 51.6], [167.5, 59.0]],
      },
      {
        name: "摆动储纱辊",
        type: "scatter",
        symbolSize: 5,
        emphasis: {
          focus: "series"
        },
        data: [[171.2, 79.1], [181.6, 78.9]],
      },
      {
        name: "夹纱板",
        type: "scatter",
        symbolSize: 5,
        emphasis: {
          focus: "series"
        },
        data: [[75.2, 179.1], [187.6, 48.9]],
      }
    ]
  };
  option && myChart.value.setOption(option);
}

let myChart1 = ref();
function getChart1() {
  var chartDom = document.querySelector(".midchart");
  myChart1.value = echarts.init(chartDom);
  var option = {
    title: {
      text: "数据融合后",
      textStyle: {
      fontSize: 15 // 设置字号为 14px
    }
    },
    grid: {
      left: "3%",
      right: "7%",
      bottom: "7%",
      containLabel: true
    },
    legend: {
      right: "15%",
      data: ["融合后数据"],
      icon: "roundRect",
      top: "5%",
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      // trigger: 'axis',
      showDelay: 0,
      formatter: function (params) {
        if (params.value.length > 1) {
          return (
            params.seriesName +
            " :<br/>" +
            params.value[0] +
            " " +
            params.value[1] +
            " "
          );
        } else {
          return (
            params.seriesName +
            " :<br/>" +
            params.name +
            " : " +
            params.value +
            " "
          );
        }
      },
      axisPointer: {
        show: true,
        type: "cross",
        lineStyle: {
          type: "dashed",
          width: 1
        }
      }
    },
    xAxis: [
      {
        type: "category",
        scale: true,
        axisLabel: {
          formatter: "{value} "
        },
        splitLine: {
          show: false
        }
      }
    ],
    yAxis: [
      {
        name: chartYName.value,
        type: "value",
        nameRotate:0.1,
        scale: true,
        axisLabel: {
          formatter: "{value} "
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: "融合后数据",
        type: "scatter",
        symbolSize: 5,
        emphasis: {
          focus: "series"
        },
        // prettier-ignore
        data: [[168.3, 54.8], [180.3, 60.7]],
      },
    ]
  };
  option && myChart1.value.setOption(option);
}

  let fileUpload = ref([]),
    fileUpList = ref([]),
    nameArr = [];
  // 选择文件时被调用，将他赋值给fileUpload
  const handleChange = (file, fileList) => {
    if (fileUpload.value.length < 3) {
      fileUpload.value.push(file);
      fileUpList.value.push(file)
      if (fileUpload.value.length > 2) {
        for (let i = 0; i < fileUpList.value.length; i++) {
          nameArr.push(fileUpload.value[i].name)
          // fileName.value = fileUpload.value[i].name + ',' + fileName.value;
        }
        fileName.value = nameArr.toString();
      }
    } else {
      message("最多添加三个文件", { type: "error" });
    }
    console.log(fileUpload.value.length)
  }

  // 开始融合
  const uploadBtn = () => {
    if (fileUpload.value) {
      b_fusion.value = "融合中..."
      fusion_res.value = "数据融合中..."
      isDisabled.value = true
      let formData = new FormData()
      formData.append("file1", fileUpload.value[0].raw)
      formData.append("file2", fileUpload.value[1].raw)
      formData.append("file3", fileUpload.value[2].raw)

      codeFusion(formData).then(res => {
        if (res.status === 200) {
          myChart.value.setOption({
            series: [
              {
                data: res.data.list1
              },
              {
                data: res.data.list2
              },
              {
                data: res.data.list3
              }
            ]
          });
          myChart1.value.setOption({
            series: [
              {
                data: res.data.prodata
              }]
          });
          if (res.data.prodata.length > 0) {
            b_fusion.value = "开始融合"
            fusion_res.value = "数据融合完成"
            isDisabled.value = false
          }
        }
      }).catch(error => {
        console.log(error)
      });
    }
  }
    //计算属性
    const tagType = computed(() => {
      if (fusion_res.value ==='未进行数据融合') {
        return 'danger'
      } else if (fusion_res.value ==='数据融合完成') {
        return 'success'
      }
    })

function handleSavePath() {
  // try {
  //   const dirHandle = window.showDirectoryPicker();
  //   // 获取选择的文件夹路径
  //   const selectedPath = dirHandle.name;
  //   if (selectedPath) {
  //     // 在这里可以处理选择的文件夹路径
  //     s_path.value = selectedPath;
  //   }
  // } catch (err) {
  //   console.error('Error selecting directory:', err);
  // }
}

function handleFileUpload() {
  if (fileUpList.value.length >= 3) {
    alert("最多只能上传三个文件！");
    return; // 中止上传
  }
  // 处理文件上传逻辑
  const inputElement = document.createElement("input");
  inputElement.type = "file";
/*   inputElement.accept = ".mat"; // 设置允许的文件类型
 */  inputElement.onchange = event => {
    const selectedFile = event.target.files[0];
    if (selectedFile) {
      // 检查文件类型
      const fileType = selectedFile.name.split('.').pop().toLowerCase();
   /*    if (fileType !== 'mat') {
        // 提示用户选择正确的文件类型
        alert("请选择 .mat 文件");
        return; // 中止上传
      }
 */
      // 文件类型验证通过，更新界面显示选定的文件名
      file.value = selectedFile.name;
      // 可以根据需要将文件信息存储在其他变量中
      fileUpList.value.push(selectedFile.name);    }
  };
  inputElement.click();

}
  function removeFile(index) {
    let arr = [];
    fileUpList.value.splice(index, 1); // 使用 splice 方法删除指定索引位置的文件
    for (let i = 0; i < fileUpList.value.length; i++) {
      arr.push(fileUpList.value[i].name)
    }
    fileName.value = arr.toString();
  }
</script>

<style>
  .el-upload-list {
    display: none;
  }
</style>
<style lang="scss" scoped>
.dataFusion {
  width: 100%;
  height: 100%;
  font-size: 16px;

  .header_1,
  .header_2 {
    width: 100%;
    height: 60px;
    line-height: 60px;
    padding-left: 20px;
    border-bottom: 1px solid #ccc;
  }

  .fusionData {
    width: 100%;
    /*height: 100px;*/
    line-height: 40px;
    padding-left: 20px;
    /*margin-bottom: 150px;
    margin-top: 20px;*/
  }

  .ids {
    width: 0;
    height: 0;
    margin-top: 0;
    padding-left: 0;

    .title {
      padding-bottom: 10px;
    }
  }

  .fuseWay {
    width: 100%;
    height: 100px;
    line-height: 40px;
    padding-left: 20px;
    margin-top: 20px;
  }

  .storePath {
    width: 100%;
    height: 100px;
    line-height: 40px;
    padding-left: 20px;
  }

  .btns {
    width: 100%;
    height: 100px;
    line-height: 40px;
    padding-left: 20px;
  }

  .over_btn {
    margin-top: 20px;
  }

  .box {
    border: black;
  }

  .upchart {
    width: 100%;
    height: 300px;
    margin-top: 20px;
  }
  .midchart {
    width: 100%;
    height: 300px;
  }
}
</style>
